#!/user/bin/env python3
# -*- coding: utf-8 -*-

import tkinter
import tkinter.messagebox
from threading import Thread
from multiprocessing import Process, Queue
from os import getpid
from random import randint
from time import time, sleep


"""
单线程的正常情况下
"""


def download_task(filename):
    print("启动下载进程，进程号[%d]." % getpid())
    print("开始下载%s..." % filename)
    time_to_download = randint(5, 10)
    sleep(time_to_download)
    print("%s下载完成！耗费了%d秒" % (filename, time_to_download))


def no_multiprocess():
    start = time()
    download_task("python从入门到住院.pdf")
    download_task("Peking So Hot.mp4")
    end = time()
    print("综合共花费了%.2f秒" % (end - start))


# print(no_multiprocess())


# 多进程
def mul_process():
    star = time()
    p1 = Process(target=download_task, args=("python从入门到住院.pdf",))
    p1.start()
    p2 = Process(target=download_task, args=("Peking So Hot.mp4",))
    p2.start()
    p1.join()
    p2.join()
    end = time()
    print("总共花费了%.2f秒。" % (end - star))


# if __name__ == '__main__':
    # mul_process()

"""
将耗时间的任务放到线程中以获得更好的用户体验
有“下载”和“关于”两个按钮，用休眠的方式模拟点击“下载”按钮会联网下载文件需要耗费10秒的时间，
如果不使用“多线程”，我们会发现，当点击“下载”按钮后整个程序的其他部分都被这个耗时间的任务阻塞而无法执行了
"""


def graphic_process():
    class DownloadTaskHandler(Thread):
        def run(self):
            sleep(10)
            tkinter.messagebox.showinfo('提示', '下载完成！')
            # 启用下载按钮
            button1.config(state=tkinter.NORMAL)

    def download():
        # 禁用下载按钮
        button1.config(state=tkinter.DISABLED)
        # 通过daemon参数将线程设置为守护线程（主程序退出就不再保留执行）
        # 在线程中处理耗时间的下载任务
        DownloadTaskHandler(daemon=True).start()

    def show_about():
        tkinter.messagebox.showinfo('about', 'author:star')

    top = tkinter.Tk()
    top.title("单线程")
    top.geometry('200x150')
    top.wm_attributes('-topmost', 1)

    panel = tkinter.Frame(top)
    button1 = tkinter.Button(panel, text='Download', command=download)
    button1.pack(side='left')
    button2 = tkinter.Button(panel, text='About', command=show_about)
    button2.pack(side='right')
    panel.pack(side='bottom')
    tkinter.mainloop()


# if __name__ == '__main__':
#     graphic_process()


# 求1-100000000的和
def task_handler(curr_list, result_queue):
    total = 0
    for number in curr_list:
        total += number
    result_queue.put(total)


def sum_1_billion():
    processes = []
    number_list = [x for x in range(1, 1000000001)]
    result_queue = Queue()
    index = 0
    # 启动8个进程将数据切片后运算
    for _ in range(8):
        p = Process(target=task_handler,
                    args=(number_list[index:index+12500000], result_queue))
        index += 12500000
        processes.append(p)
        p.start()
    start = time()
    for p in processes:
        p.join()
    total = 0
    while not result_queue.empty():
        total += result_queue.get()
    print(total)
    end = time()
    print('Execution time:', (end - start), 's', sep='')


# if __name__ == '__main__':
#     sum_1_billion()
